import Vue from 'vue';
import Router from 'vue-router';
import system from './router/system';
import store from './store/store';
import { isString, isPlainObject } from 'lodash';
Vue.use(Router);

import Login from '@/view/login/Login.vue';
import Index from '@/view/index/Index.vue';
const routes = [
    {
        path: '/',
        component:Index,
        meta: { title: '首页' },
        children: [...system],
        redirect: '/home'
    },
    {
        path: '/login',
        component: Login,
        meta: { title: '登录' }
    },
];

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};
const router = new Router({ mode: 'history', routes, base: (process.env.NODE_ENV === 'development' ? '' : '/weChatApp') });


//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    document.title = `${to.meta.title?to.meta.title:'哲人石'}`;
    if(to.query.shareOpenId && isString(to.query.shareOpenId)){
      window.sessionStorage.setItem('ZRS_USER_SHARE_OPENID',to.query.shareOpenId);
    }
    const userInfo = store.state.app.ZRSUserInfo;
    const isLogin = userInfo && isPlainObject(userInfo) && userInfo.openid && isString(userInfo.openid) ? true : false;
    if (!isLogin && to.path !== '/login') {
        if(to.path!='/' && to.path!='/home'){
            window.localStorage.setItem('setLoginBackRedirectUrl',to.fullPath)
        }
        next('/login')
    } else {
        next();
    }
});

export default router;
